package com.cmc.cloud.cmclink.doc.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.cmc.cloud.cmclink.doc.api.document.rep.HsCodeRespDto;
import com.cmc.cloud.cmclink.doc.api.document.req.HsCodeReqDto;
import com.cmc.cloud.cmclink.doc.constants.UrlConstants;
import com.cmc.cloud.cmclink.doc.entity.HsCodeDO;
import com.cmc.cloud.cmclink.doc.framework.listener.HsCodeExcelListener;
import com.cmc.cloud.cmclink.doc.service.HsCodeService;
import com.cmc.cloud.cmclink.doc.vo.hscodevo.*;
import com.cmes.framework.biz.advice.annotations.UseResponsePropertyAdvice;
import com.cmes.framework.common.pojo.CommonResult;
import com.cmes.framework.common.pojo.PageResult;
import com.cmes.framework.excel.core.util.ExcelUtils;
import com.cmes.framework.operatelog.core.annotations.OperateLog;
import com.cmes.framework.operatelog.core.enums.OperateTypeEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;


/**
 * {table.classComment}前端接口Controller
 * 
 * @author codegen
 */
@Tag(name = "管理后台 - hscode")
@RestController
@RequestMapping(UrlConstants.APPLICATION_URL+"/hsCode")
@Validated
public class HsCodeController {

    @Resource
    private HsCodeService hsCodeService;

    @Operation(summary = "创建hscode")
    @PostMapping("/create")
    @PreAuthorize("@ss.hasPermission('doc:maintainHSCodeCommodity:add')")
    public CommonResult<Void> createHsCode(@Valid @RequestBody HsCodeCreateReqVO createReqVO) {
        hsCodeService.createHsCode(createReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "更新hscode")
    @PostMapping("/update")
    @PreAuthorize("@ss.hasPermission({'doc:maintainHSCodeCommodity:edit','doc:maintainHSCodeCommodity:enable'})")
    public CommonResult<Void> updateHsCode(@Valid @RequestBody HsCodeUpdateReqVO updateReqVO) {
        hsCodeService.updateHsCode(updateReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "删除hscode")
    @Parameter(name = "id", description = "编号", required = true)
    @PostMapping("/delete/{id}")
    @PreAuthorize("@ss.hasPermission('doc:maintainHSCodeCommodity:delete')")
    public CommonResult<Void> deleteHsCode(@PathVariable("id") Long id) {
        hsCodeService.deleteHsCode(id);
        return CommonResult.success();
    }

    @Operation(summary = "删除hscode全部数据")
    @PostMapping("/deleteAll")
    @PreAuthorize("@ss.hasPermission('doc:maintainHSCodeCommodity:deleteAllExportData')")
    public CommonResult<Void> deleteAllHsCode() {
        hsCodeService.deleteHsCode();
        return CommonResult.success();
    }

    @Operation(summary = "获得hscode")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @GetMapping("/getById/{id}")
    public CommonResult<HsCodeRespVO> getHsCode(@PathVariable("id") Long id) {
        HsCodeDO hsCode = hsCodeService.getHsCode(id);
        return CommonResult.success(BeanUtil.copyProperties(hsCode, HsCodeRespVO.class));
    }

    @Operation(summary = "获得hscode列表")
    @GetMapping("/listAll")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    public CommonResult<List<HsCodeRespVO>> getHsCodeList(@RequestParam("ids") Collection<Long> ids) {
        List<HsCodeDO> list = hsCodeService.getHsCodeList(ids);
        return CommonResult.success(BeanUtil.copyToList(list,HsCodeRespVO.class));
    }

    @Operation(summary = "获得hscode分页")
    @PostMapping("/getPage")
    @UseResponsePropertyAdvice
    @PreAuthorize("@ss.hasPermission('doc:maintainHSCodeCommodity:search')")
    public CommonResult<PageResult<HsCodeRespVO>> getHsCodePage(@Valid @RequestBody HsCodePageReqVO pageVO) {
        PageResult<HsCodeDO> pageResult = hsCodeService.getHsCodePage(pageVO);
        List<HsCodeRespVO> results = BeanUtil.copyToList(pageResult.getList(), HsCodeRespVO.class);
        return CommonResult.success(new PageResult<>(results, pageResult.getTotal()));
    }

    @Operation(summary = "获得hscode全部")
    @PostMapping("/getAllList")
    public CommonResult<List<HsCodeRespDto>> getAllList(@Valid @RequestBody HsCodeReqDto hsCodeReqDto) {
        return CommonResult.success(hsCodeService.queryHsCodeInfo(hsCodeReqDto));
    }

    @GetMapping("/excel-template")
    @Operation(summary = "下载excel导入模板")
    public void downloadExcelTemplateImport(HttpServletResponse response) throws IOException {
        List<HsCodeExportVo> list = Arrays.asList(
                HsCodeExportVo.builder().hsCode("code").descEn("code英文名").descCn("code中文名")
                        .build()
        );
        // FIXME 一定要向response写数据之前设置响应头，否则会出现文件下载失败
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("hscode编码导入模板.xlsx", StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        ExcelUtils.write(response, "hscodeImportTemplate.xls", "模版", HsCodeExportVo.class, list);

    }

    @GetMapping("/excel-export")
    @Operation(summary = "excel导出")
    @PreAuthorize("@ss.hasPermission('doc:maintainHSCodeCommodity:export')")
    public void exportExcelTemplate(HttpServletResponse response) throws IOException {
        List<HsCodeExportVo> exportList = hsCodeService.getExportList();
        // FIXME 一定要向response写数据之前设置响应头，否则会出现文件下载失败
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("hscode编码导入模板.xlsx", StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        ExcelUtils.write(response, "hscodeData.xls", "模版", HsCodeExportVo.class, exportList);

    }

    @OperateLog(type= OperateTypeEnum.CREATE)
    @PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "excel新增导入")
    @PreAuthorize("@ss.hasPermission('doc:maintainHSCodeCommodity:import')")
    public CommonResult<Integer> excelCreateImport(@RequestPart @RequestParam(value ="file") MultipartFile file) throws IOException {
        HsCodeExcelListener hsCodeExcelListener = new HsCodeExcelListener(new ArrayList<>());
        List<HsCodeImportVo> importVos = EasyExcel.read(file.getInputStream(), HsCodeImportVo.class, hsCodeExcelListener).autoCloseStream(true).doReadAllSync();
        Integer num = hsCodeService.saveImportData(importVos);
        return CommonResult.success(num);
    }
}
